import { nextTick, ref, watch } from 'vue';
import { createUniver, defaultTheme, LocaleType, Tools, FUniver, Univer } from '@univerjs/presets';
import { UniverSheetsCorePreset } from '@univerjs/presets/preset-sheets-core';
import { UniverSheetsDataValidationPreset } from '@univerjs/presets/preset-sheets-data-validation'
import { UniverSheetsConditionalFormattingPreset } from '@univerjs/presets/preset-sheets-conditional-formatting'


import UniverPresetSheetsCoreZhCN from '@univerjs/presets/preset-sheets-core/locales/zh-CN';
import UniverPresetSheetsDataValidationZhCN from '@univerjs/presets/preset-sheets-data-validation/locales/zh-CN'
import UniverPresetSheetsConditionalFormattingZhCN from '@univerjs/presets/preset-sheets-conditional-formatting/locales/zh-CN'
//@ts-ignore
import _ from 'lodash';
import '@univerjs/presets/lib/styles/preset-sheets-core.css';
import '@univerjs/presets/lib/styles/preset-sheets-data-validation.css'
import '@univerjs/presets/lib/styles/preset-sheets-conditional-formatting.css'
export let univerAPI: FUniver;
export let sourceUniver: Univer
export function initExcel(el: string, data = {}) {
  // if (!univerAPI && el) {
  if (el) {

    const univer = createUniver({
      locale: LocaleType.ZH_CN,
      locales: {
        zhCN: Tools.deepMerge(
          {},
          UniverPresetSheetsCoreZhCN,
          UniverPresetSheetsDataValidationZhCN,
          UniverPresetSheetsConditionalFormattingZhCN
        )
      },
      theme: defaultTheme,
      presets: [
        UniverSheetsCorePreset({
          container: el
          // header: false,
          // contextMenu: false
        }),
        UniverSheetsDataValidationPreset(),
        UniverSheetsConditionalFormattingPreset()
      ],
      plugins: [

      ]
    })
    univerAPI = univer.univerAPI
    sourceUniver = univer.univer
    univerAPI.createUniverSheet(_.cloneDeep(data))
    univerAPI.onBeforeCommandExecute((command) => {
      console.log(command.id)
    })
  } else {
    reload(data)
  }
}
// 重新加载数据
export const reload = (data = {}) => {
  univerAPI.createUniverSheet(_.cloneDeep(data))
}

export const dispose = () => {
  const activeWorkbook = univerAPI?.getActiveWorkbook()
  const unitId = activeWorkbook && activeWorkbook.getId()
  unitId && univerAPI.disposeUnit(unitId)
  sourceUniver.dispose()
}